package com.wzq.app.api;


import android.text.TextUtils;
import android.util.Log;

import com.wzq.app.BusApplication;
import com.wzq.app.utils.FilePathUtils;
import com.wzq.app.utils.NetworkUtils;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.CacheControl;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 */
public class Api {
    public Retrofit retrofit;
    public ApiService service;

    public static final String BASE_TEST_URL = "http://192.168.3.5:8081/";
//        public static final String BASE_TEST_URL = "http://47.114.185.188:8080/";
    public static final String VIDEO_URL = BASE_TEST_URL + "video/";

    private static class SingletonHolder {
        private static final Api INSTANCE = new Api();
    }


    public static Api getInstance() {
        return SingletonHolder.INSTANCE;
    }


    //构造方法私有
    private Api() {
        HttpLoggingInterceptor logInterceptor = new HttpLoggingInterceptor();
        logInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        File cacheFile = new File(FilePathUtils.getCachePath(), "cache");
        Cache cache = new Cache(cacheFile, 1024 * 1024 * 10); //10Mb
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .readTimeout(15, TimeUnit.SECONDS)
                .connectTimeout(15, TimeUnit.SECONDS)
                .addInterceptor(new ParamsInterceptor())
                .addInterceptor(logInterceptor)
                .addNetworkInterceptor(new HttpCacheInterceptor())
                .cache(cache)
                .build();

        retrofit = new Retrofit.Builder()
                .client(okHttpClient)
                .addConverterFactory(GsonConverterFactory.create())
                .baseUrl(BASE_TEST_URL)
                .build();
        service = retrofit.create(ApiService.class);
    }


    class ParamsInterceptor implements Interceptor {

        @Override
        public Response intercept(Chain chain) throws IOException {
            Request original = chain.request();
            HttpUrl.Builder authorizedUrlBuilder = original.url()
                    .newBuilder()
                    .scheme(original.url().scheme())
                    .host(original.url().host());
            Request newRequest = original.newBuilder()
                    .method(original.method(), original.body())
                    .url(authorizedUrlBuilder.build())
                    .build();
            return chain.proceed(newRequest);
        }
    }

    class HttpCacheInterceptor implements Interceptor {

        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            if (!NetworkUtils.isConnected(BusApplication.mApplicationContext)) {
                request = request.newBuilder()
                        .cacheControl(CacheControl.FORCE_CACHE)
                        .build();
                Log.d("Okhttp", "no network");
            }

            Response originalResponse = chain.proceed(request);
            if (!NetworkUtils.isConnected(BusApplication.mApplicationContext)) {
                int maxAge = 60 * 60 * 24 * 7; // 在线缓存在7天内可读取
                String cacheControl = request.cacheControl().toString();
                Response.Builder builder = originalResponse.newBuilder();
                if (TextUtils.isEmpty(cacheControl)) {
                    builder.header("Cache-Control", "public, only-if-cached, max-stale=" + maxAge);
                } else {
                    builder.header("Cache-Control", cacheControl);
                }
                builder.removeHeader("Pragma")
                        .build();
            }
            return originalResponse;
        }
    }
}